package com.hunantv.mglive.ui.discovery.publisher.pic;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.util.DisplayMetrics;
import android.widget.ImageView;

import com.hunantv.mglive.utils.ImageUtilsEx;
import com.hunantv.mglive.utils.L;

/**
 * @author maxxiang
 * 多线程截剪bitmap类，用于缩略图列表的显示
 * Create On: 2015-12-9
 */
public class AsyncImageLoader {
	public void asyncLoadImage(final ImageView imgView, final String imageUrl, final int position) {
		
		String strUrl = (String) imgView.getTag();
		if(strUrl == imageUrl)
			return;//不需要重复发送。。。。
		
		imgView.setTag(imageUrl);
		
		PicDecodeThreadPool.instance().postToWorkThread(new Runnable() {
			@Override
			public void run() {
				String strUrl = (String) imgView.getTag();
				if (strUrl != imageUrl && strUrl != null) {
					L.d("grid", "asyncLoadImage has been cancel");
					return;
				}
				
				L.d("grid", "asyncLoadImage:" + imageUrl);

				Bitmap bm = loadImageFromUrl(imageUrl);
				if(bm != null){
					PicCache.getInstance().putBitmap(imageUrl, bm); // 采用全局的缩略图缓存
				}
				
				LoadImageFinishedRunnable r = new LoadImageFinishedRunnable(imgView, bm, imageUrl);
				PicDecodeThreadPool.instance().postToMainThread(r);

			}
		},position);
	}
	
	//位图显示渐变动画
	private void setImageBitmap(ImageView imageView, Bitmap bitmap, boolean isTran) {
		if (isTran) {
			final TransitionDrawable td = new TransitionDrawable(new Drawable[] { new ColorDrawable(android.R.color.transparent), new BitmapDrawable(bitmap) });
			td.setCrossFadeEnabled(true);
			imageView.setImageDrawable(td);
			td.startTransition(300);

		} else {
			imageView.setImageBitmap(bitmap);
		}
	}
	
	class LoadImageFinishedRunnable implements Runnable{
		
		private ImageView mView;
		private Bitmap mBitmap;
		private String mUrl;
		
		public LoadImageFinishedRunnable(ImageView imgView, Bitmap bm, String imageUrl){
			mView = imgView;
			mBitmap = bm;
			mUrl =imageUrl;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			String strUrl = String.valueOf(mView.getTag());

			if (mView != null && strUrl == mUrl) {
				//mView.setImageBitmap(mBitmap);
				setImageBitmap(mView,mBitmap,true);
			}
		}
	}

	public Bitmap loadImageFromUrl(String url) {
		Bitmap bitmap = null;
		try {
			Options options = new Options();
			options.inJustDecodeBounds = true;
			options.inPreferredConfig = Bitmap.Config.RGB_565; // maxxiang 为了节省内存
			options.inDensity = DisplayMetrics.DENSITY_DEFAULT;
			options.inTargetDensity = DisplayMetrics.DENSITY_DEFAULT;
			options.inScreenDensity = DisplayMetrics.DENSITY_DEFAULT;
			BitmapFactory.decodeFile(url, options);

			// 重新decode
			options.inJustDecodeBounds = false;
			options.inSampleSize = ImageUtilsEx.findBestSampleSize(options.outWidth, options.outHeight, PicQueryConstants.RECENT_PHOTO_MIN_WIDTH, PicQueryConstants.RECENT_PHOTO_MIN_WIDTH);
			// calculateInSampleSize(options, PicQueryConstants.RECENT_PHOTO_MIN_WIDTH, PicQueryConstants.RECENT_PHOTO_MIN_WIDTH);
			bitmap = BitmapFactory.decodeFile(url, options);
		} catch (OutOfMemoryError exception) {

			L.d("img", "loadImageFromUrl : out of memory image: " + url);
		}

		return bitmap;
	}
	
	private int calculateInSampleSize(Options options, int reqWidth, int reqHeight)
	{
		if (reqWidth == 0 || reqHeight == 0 || reqWidth == -1 || reqHeight == -1)
		{
			return 1;
		}
		// Raw height and width of image
		int height = options.outHeight;
		int width = options.outWidth;
		int inSampleSize = 1;

		while (height > reqHeight && width > reqWidth)
		{
			final int heightRatio = Math.round((float) height / (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			int ratio = heightRatio > widthRatio ? heightRatio : widthRatio;
			if (ratio >= 2)
			{
				width /= 2;
				height /= 2;
				inSampleSize *= 2;
			}
			else
			{
				break;
			}
		}
		return inSampleSize;
	}

}
